﻿namespace Example.Structural.Proxy
{
    using System;
    using System.Drawing;
    using System.Net;

    public sealed class Favicon
    {
        private Image _image;

        public Favicon(Uri uri)
        {
            Location = new Uri(uri, new Uri("/favicon.ico", UriKind.Relative));
        }

        public Image Image
        {
            get
            {
                if (null == _image)
                {
                    var request = (HttpWebRequest)WebRequest.Create(Location);
                    request.Method = "GET";
                    request.AllowAutoRedirect = true;
                    using (var response = GetResponse(request))
                    {
                        if (HttpStatusCode.OK ==
                            response.StatusCode)
                        {
                            using (var stream = response.GetResponseStream())
                            {
                                if (null != stream)
                                {
                                    _image = Image.FromStream(stream);
                                }
                            }

                            Location = response.ResponseUri;
                        }
                    }
                }

                return _image;
            }
        }

        public Uri Location { get; private set; }

        private static HttpWebResponse GetResponse(WebRequest request)
        {
            HttpWebResponse result;

            try
            {
                result = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException exception)
            {
                result = (HttpWebResponse)exception.Response;
            }

            return result;
        }
    }
}